package MyBinaryTree;

public class Inorder_PostorderCreateTree {
    public int i;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        i = inorder.length  -1;
        return buildTree2(inorder, postorder, 0, postorder.length - 1);
    }

    public TreeNode buildTree2(int[] inorder, int[] postorder, int ib, int ie) {
        if (i < 0 || ie < ib) {
            return null;
        }
        int num = postorder[i];
        TreeNode root = new TreeNode(num);
        i--;
        int j = 0;
        for ( ; j < inorder.length; j++) {
            if (inorder[j] == num) {
                break;
            }
        }
        root.rightNode = buildTree2(inorder, postorder, j + 1, ie);
        root.leftNode = buildTree2(inorder, postorder, ib, j - 1);
        return root;
    }
}
